$(function() {

    var automaticAdd = false;

    var currentConnection = null;
    var deletingConnection = null;
    var deletingPlanet = null;

    function getRealIdFromFake(fakeId) {
        var tokens = fakeId.split("-");
        return tokens.pop();
    }

    /* Prende in input una stringa tipo #FFFFFF o FFFFFF e ritorna un oggetto cha ha proprietà rbg decimali
     * 
     * @param {String} hex
     * @returns Una struttura con proprietà r, g, b. Ognuna rappresentante la proprietà del colore.
     */
    function hexToRgb(hex) {
        // nel caso venga passato il cancelletto lo elimina dalla stringa
        hex.replace("#", "");
        // Espande la forma a triplete (tipo "03F") nella forma estesa (analogamente "0033FF")
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, function(m, r, g, b) {
            return r + r + g + g + b + b;
        });

        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }
    /* Traduce un componente decimale in HEX
     * 
     * @param {String} c
     * @returns {String}
     */
    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }

    /* Prende in input i valori RGB e ritorna una stringa in esadecimale tipo #FFFFFF
     * 
     * @param {String} r
     * @param {String} g
     * @param {String} b
     * @returns {String} tipo #FFFFFF
     */
    function rgbToHex(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }

    connections = [],
            updateConnections = function(conn) {
        // metto in un array globale

        if (connections.length > 0) {
            //connections = connections.sort();
            console.log("Connection NON VUOTO");
            for (var j = 0; j < connections.length; j++) {
                console.log("check connessione ", connections[j].id);
                if ((conn.sourceId === connections[j].sourceId && conn.targetId === connections[j].targetId) ||
                        (conn.sourceId === connections[j].targetId && conn.targetId === connections[j].sourceId)) {
                    //console.log("Trovate connessioni uguali "+connections[j].id,+" - "+connections[j+1].id);
                    //results.push(connections[j]);
                    return false;
                }

            }
            console.log("Aggiornata lista connessioni: ", conn.id);
            connections.push(conn);


        } else {
            console.log("Connection VUOTO");
            console.log("Aggiornata lista connessioni: ", conn.id);
            connections.push(conn);
        }
        // aggiunta cosa db
        return true;
    };

    $("#color-confirm").click(function() {
        var realSourceId = getRealIdFromFake(currentConnection.sourceId);
        var realTargetId = getRealIdFromFake(currentConnection.targetId);
        var decimalColor = hexToRgb($("#currentColor").val());

//        currentConnection.getOverlay("label").setLabel(decimalColor.r + ", " + decimalColor.g + ", " + decimalColor.b);
        currentConnection.setPaintStyle({
            lineWidth: 3,
            strokeStyle: "rgba(" + decimalColor.r + "," + decimalColor.g + "," + decimalColor.b + ",0.5)",
            joinstyle: "round"
                    //outlineColor:transparent,
                    //outlineWidth:7
        });

        $.post("/connectionsServlet", {
            startPlanet: realSourceId,
            endPlanet: realTargetId,
            actionToDo: "insert",
            red: decimalColor.r,
            green: decimalColor.g,
            blue: decimalColor.b
        }).done(function(data) {
//            alert("Connessione tra " + realSourceId + " e " + realTargetId + " inserita con colore " + decimalColor.r + ", " + decimalColor.g + ", " + decimalColor.b);
        });

    });
    $("#color-cancel").click(function() {
        var realSourceId = getRealIdFromFake(currentConnection.sourceId);
        var realTargetId = getRealIdFromFake(currentConnection.targetId);

        $.post("/connectionsServlet", {
            startPlanet: realSourceId,
            endPlanet: realTargetId,
            actionToDo: "insert",
            red: 255,
            green: 255,
            blue: 255
        }).done(function(data) {
//            alert("Connessione tra " + realSourceId + " e " + realTargetId + " inserita senza colore ");
        });
    });



    window.jsPlumbDemo = {
        init: function() {

            jsPlumb.importDefaults({
                // default drag options
                DragOptions: {cursor: 'pointer', zIndex: 2000},
                // default to blue at one end and green at the other
                EndpointStyles: [{fillStyle: '#558822'}],
                // blue endpoints 7 px; green endpoints 11.
                Endpoints: [["Dot", {radius: 11}]]
                        // the overlays to decorate each connection with.  note that the label overlay uses a function to generate the label text; in this
                        // case it returns the 'labelText' member that we set on each connection in the 'init' method below.
//                ConnectionOverlays: [
//                    //[ "Arrow", { location:0.9 } ],
//                    ["Label", {
//                            location: 0.5,
//                            id: "label",
//                            cssClass: "aLabel"
//                        }]
//                ]
            });

            // this is the paint style for the connecting lines..
            var whiteColor = "rgba(255,255,255,0.5)";
            var redColor = "rgba(255, 165, 0,0.5)";
            var transparent = "rgba(0, 0, 0,0)";
            var connectorPaintStyle = {
                lineWidth: 3,
                strokeStyle: whiteColor,
                joinstyle: "round",
                //outlineColor:transparent,
                //outlineWidth:7
            },
                    // .. and this is the hover style. 
                    connectorHoverStyle = {
                lineWidth: 3,
                strokeStyle: redColor
            },
            // the definition of source endpoints (the small blue ones)
            sourceEndpoint = {
                endpoint: "Dot",
                paintStyle: {fillStyle: whiteColor, radius: 15},
                isSource: true,
                isTarget: true,
                connector: ["Straight", /*{ stub:[40, 60], gap:10 }*/],
                connectorStyle: connectorPaintStyle,
                //hoverPaintStyle:connectorHoverStyle,
                connectorHoverStyle: connectorHoverStyle,
                dragOptions: {},
                beforeDrop: function(params) {
                    return updateConnections(params.connection);
                },
                maxConnections: -1
            },
            // a source endpoint that sits at BottomCenter
            //	bottomSource = jsPlumb.extend( { anchor:"BottomCenter" }, sourceEndpoint),
            // the definition of target endpoints (will appear when the user drags a connection) 
            targetEndpoint = {
                endpoint: "Dot",
                paintStyle: {fillStyle: "#558822", radius: 11},
                hoverPaintStyle: connectorHoverStyle,
                maxConnections: -1,
                dropOptions: {hoverClass: "hover", activeClass: "activeConn"},
                isTarget: true
//                overlays: [
//                    ["Label", {location: [0.5, -0.5], label: "Drop", cssClass: "endpointTargetLabel"}]
//                ]
            };


            var allSourceEndpoints = [];
            _addEndpoints = function(toId, sourceAnchors, targetAnchors) {
                for (var i = 0; i < sourceAnchors.length; i++) {
                    var sourceUUID = toId + sourceAnchors[i];
                    allSourceEndpoints.push(jsPlumb.addEndpoint(toId, sourceEndpoint, {anchor: sourceAnchors[i], uuid: sourceUUID}));
                }

            };


            // listen for new connections; initialise them the same way we initialise the connections at startup.
            jsPlumb.bind("jsPlumbConnection", function(connInfo, originalEvent) {
                init(connInfo.connection);
            });

            // make all the window divs draggable						
            jsPlumb.draggable(jsPlumb.getSelector(".window"), {
                stop: function() {
                    var planetId = getRealIdFromFake($(this).attr("id"));
                    var x = $(this).css("left").replace("px", "");
                    var y = $(this).css("top").replace("px", "");

                    $.post("/connectionsServlet", {
                        planetMoved: planetId,
                        setX: x,
                        setY: y
                    }).done(function(data) {
//                        alert("Aggiornata posizione sul db di: " + planetId + " con punto " + x + ", " + y);
                    });
                }
            });

            //
            // listen for clicks on connections, and offer to delete connections on click.
            //
            jsPlumb.bind("click", function(conn, originalEvent) {
//                alert(conn.getType());
                // conn.setType();
                deletingConnection = conn;
                conn.strokeStyle = 'rgba(0,255,0,0.7)';
                conn.repaint();

                var sourcePlanet = $("#" + conn.sourceId).attr("title");
                var destPlanet = $("#" + conn.targetId).attr("title");

                $("#myModalLabel2").text("Conferma eliminazione");
                $("#myModal2 .modal-body p").text("Vuoi cancellare la connessione tra il pianeta " + sourcePlanet + " e " + destPlanet + " ?");
                $('#myModal2').modal('show');

            });

            jsPlumb.bind("connectionDrag", function(connection) {
                console.log("Inizio a tracciare " + connection.id);
            });

            jsPlumb.bind("connectionDragStop", function(connection) {
                console.log("Connessione " + connection.id + " tracciata e posizionata");

            });

            jsPlumb.bind("connection", function(info, originalEvent) {
                //updateConnections(info.connection);

                currentConnection = info.connection;

                if (!automaticAdd) { // flag che permette di sapere se sono connesisoni aggiunte dal server o dall'utente
                    $("#connectionModalLabel").text("Scegli un colore della connessione");
                    $('#connectionModal').modal('show');
                }
//                alert(info.connection.id);

            });
        }
    };

    $("#delete-conn-confirm").click(function() {

        var realSourceId = getRealIdFromFake(deletingConnection.sourceId);
        var realTargetId = getRealIdFromFake(deletingConnection.targetId);

        $.post("/connectionsServlet", {
            startPlanet: realSourceId,
            endPlanet: realTargetId,
            actionToDo: "delete"
        }).done(function(data) {
//            alert("Connessione tra " + realSourceId + " e " + realTargetId + " eliminata");
        });

        jsPlumb.detach(deletingConnection);
        connections.splice(connections.indexOf(deletingConnection)); // rimuove dalla lista connessioni
    });

    var popover_show = new Boolean();
    var timeoutID;

    var globalIdPlanet;
    var currentActiveTab;
    var planetsArray = [];
    var globalIdUniverse = $("#universe_id").attr("data-id");

    var planetSelected = false;

    /** Gestione delle tab ADMINISTRATOR**/
    
    var currentSelectedUser;
    var currentSelectedUserPrivs;
    var currentSelectedUniverse;
    var currentSelectedUniverseCreator;
    var currentSelectedUniverseValidation;
    
    /*
     * Gestione Bottoni lista utenti lato amministratore
     */
    function enableAdminController(){
        /**
         * Parte controllo utenti
         */
        $("#admin-users table tbody").on("click",".edit-user", function(e){
            e.preventDefault();
            
            var selectedUserRow = $(this).parent().parent();
            var selectedUserId = selectedUserRow.attr("id");
            currentSelectedUser = getRealIdFromFake(selectedUserId);
            currentSelectedUserPrivs = getRealIdFromFake($("td.privileges", selectedUserRow).attr("data-privileges"));
            
            var selectedUserName = $("td:first-child", selectedUserRow).text();
//            alert(currentSelectedUserPrivs);
            
            $("#adminModalEditLabel").html("Modifica privilegi");
            $("#adminModalEdit .modal-body p").html("Puoi modificare i privilegi dell'utente <strong>" + selectedUserName + "</strong> cliccando su uno dei seguenti pulsanti:");
            switch (currentSelectedUserPrivs)
            {
                case "2":
                    $("#admin-setadmin-button").html("Utente gi&agrave; amministratore");
                    $("#admin-setadmin-button").addClass("disabled");
                    $("#admin-setadmin-button").attr("disabled","disabled");
                    
                    $("#admin-setcreator-button").html("Cambia in <strong>creatore</strong>");
                    $("#admin-setcreator-button").removeClass("disabled");
                    $("#admin-setcreator-button").removeAttr("disabled");
                    break;
                case "1":
                    $("#admin-setcreator-button").html("Utente gi&agrave; creatore");
                    $("#admin-setcreator-button").addClass("disabled");
                    $("#admin-setcreator-button").attr("disabled","disabled");
                    
                    $("#admin-setadmin-button").html("Cambia in <strong>amministratore</strong>");
                    $("#admin-setadmin-button").removeClass("disabled");
                    $("#admin-setadmin-button").removeAttr("disabled");
                    break;
                default:
                    $("#admin-setadmin-button").html("Valida come <strong>amministratore</strong>");
                    $("#admin-setcreator-button").html("Valida come <strong>creatore</strong>");
            }
            
            $('#adminModalEdit').modal('show');
            
        });
        $("#admin-users table tbody").on("click", ".delete-user", function(e){
            e.preventDefault();
            var selectedUserRow = $(this).parent().parent();
            var selectedUserId = selectedUserRow.attr("id");
            currentSelectedUser = getRealIdFromFake(selectedUserId);
            var selectedUserName = $("td:first-child", selectedUserRow).text();
            
            $("#adminModalDeleteLabel").html("Conferma eliminazione utente");
            $("#adminModalDelete .modal-body p").html("Vuoi cancellare l'Utente <strong>" + selectedUserName + "</strong> ?");
            $('#adminModalDelete').modal('show');
        });
        
        $("#admin-confirm-button").on("click", function(e){
            e.preventDefault();
            
            $.post("/AdminUserServlet", {
                idUser: currentSelectedUser,
                action: "delete"
            }).done(function(data) {
                getAllUsers(false);
            });
        });
        
        $("#admin-setadmin-button,#admin-setcreator-button").on("click", function(e){
            e.preventDefault();
            
            var tokens = $(this).attr("id").split("-");
            var priv = tokens[1].substring(3);
            
            $.post("/AdminUserServlet", {
                idUser: currentSelectedUser,
                action: "edit",
                privilege: priv
            }).done(function(data) {
                getAllUsers(false);
            });
        });
        
        /**
         * Parte controlli universi
         */
        $("#admin-universe table tbody").on("click", ".admin-planet-action-accept", function(e){
            e.preventDefault();
            var selectedUniverseRow = $(this).parent().parent(); // tr
            
            var selectedUniverseId = selectedUniverseRow.attr("id");
            currentSelectedUniverse = getRealIdFromFake(selectedUniverseId); // ottengo l'id dell'universo
            var selectedUniverseName = $("td:first-child", selectedUniverseRow).text(); // ottengo il nome dell'universo
            
            var creatorId = $(".creator-name", selectedUniverseRow).attr("id");
            currentSelectedUniverseCreator = getRealIdFromFake(creatorId); //ottengo l'id del creatore dell'universo
            
            $("#adminModalAcceptUniverseLabel").html("Conferma pubblicazione universo");
            $("#adminModalAcceptUniverse .modal-body p").html("Vuoi validare l'universo <strong>" + selectedUniverseName + "</strong> e pubblicarlo sulla piattaforma MuMu?");
            $('#adminModalAcceptUniverse').modal('show');
        });
        
        $("#admin-universe table tbody").on("click", ".admin-planet-action-reject", function(e){
            
            e.preventDefault();
            var selectedUniverseRow = $(this).parent().parent();
            
            var selectedUniverseId = selectedUniverseRow.attr("id");
            currentSelectedUniverse = getRealIdFromFake(selectedUniverseId); // ottengo l'id dell'universo
            var selectedUniverseName = $("td:first-child", selectedUniverseRow).text(); // ottengo il nome dell'universo
            
            var creatorId = $(".creator-name", selectedUniverseRow).attr("id");
            currentSelectedUniverseCreator = getRealIdFromFake(creatorId); //ottengo l'id del creatore dell'universo
            
            $("#adminModalDeleteUniverseLabel").html("Conferma eliminazione universo");
            $("#adminModalDeleteUniverse .modal-body p").html("Vuoi eliminare l'universo <strong>" + selectedUniverseName + "</strong>?<br /><strong>Nota:</strong> questa operazione &egrave; irreversibile!");
            $('#adminModalDeleteUniverse').modal('show');
        });
        $("#admin-universe table tbody").on("click", ".admin-planets", function(e){
            e.preventDefault();
            var selectedUniverseRow = $(this).parent().parent();
            
            var selectedUniverseId = selectedUniverseRow.attr("id");
            currentSelectedUniverse = getRealIdFromFake(selectedUniverseId); // ottengo l'id dell'universo
            var selectedUniverseName = $("td:first-child", selectedUniverseRow).text(); // ottengo il nome dell'universo
            
            var creatorId = $(".creator-name", selectedUniverseRow).attr("id");
            currentSelectedUniverseCreator = getRealIdFromFake(creatorId); //ottengo l'id del creatore dell'universo
            
            $("#admin-planets .no-planets strong").text(selectedUniverseName);
            $("#admin-planets caption").html("Pianeti dell'universo <strong>"+selectedUniverseName+"</strong>");
            
            getPlanets(currentSelectedUniverse);
            
            $("#myCarousel").carousel('next');
            
        });
        
        $("#admin-reject-universe-button, #admin-accept-universe-button").on("click", function(e){
            e.preventDefault();
            
            var tokens = $(this).attr("id").split("-");
            var action = tokens[1];
//            alert("azione: "+action+", idUniverse: "+currentSelectedUniverse+", idCreator: "+currentSelectedUniverseCreator);
            $.post("/AdminUniverseServlet", {
                action: action,
                idUniverse: currentSelectedUniverse,
                idCreator: currentSelectedUniverseCreator
            }).done(function(data) {
                getAllUniverse();
            });
        });
        /**
         * Gestione checkbox per il controllo del pianeta
         */
        $("#admin-planets table tbody").on("click","input:checkbox",function(e) {
            
            var isChecked = 0;
            if($(this).is(":checked"))
                isChecked = 1;
            
            var realIdPlanet = getRealIdFromFake($(this).parent().parent().attr("id"));
            $.post("/AdminUniverseServlet", {
                action: "checked",
                idPlanet: realIdPlanet,
                checked: isChecked
            }).done(function(data) {
                
            });
            
        });
        
        /**
         * Gestione visualizzatore contenuti
         */
        $("#admin-planets table tbody").on("click",".set-happy",function(e) {
            e.preventDefault();
            var type = getRealIdFromFake($(this).parent().attr("class"));
            var idPlanet = getRealIdFromFake($(this).parent().parent().attr("id"));
            var position = findIdPlanetInPlanetObjs(idPlanet);
//            alert(position);
            var writeHtml = "";
            switch (type)
            {
                case "image":
                    $("#adminModalImageViewLabel").html("Immagini felici");
                    // carico lista immagini
                    var description = planetsObjs[position].happyImageSetDesc;
//                    alert("description lunga: "+description.length);
                    if(description.length <= 1){
//                        alert("è vuota");
                        description = "- Nessuna descrizione fornita -";
                    }
                    $.each(planetsObjs[position].happyImageSet, function(i){
                        if(i == 0)
                            writeHtml += "<div class=\"active item\"><img src=\"Universes/"+this+"\" /><div class=\"carousel-caption\"><h4>Descrizione</h4><p>"+description+"</p></div></div>";
                        else
                            writeHtml += "<div class=\"item\"><img src=\"Universes/"+this+"\" /><div class=\"carousel-caption\"><h4>Descrizione</h4><p>"+description+"</p></div></div>";
                        
                    });
                    $('#image-carousel .carousel-inner').html(writeHtml);
                    $('#adminModalImageView').modal('show');
                    break;
                case "video":
                    // nella finestra modale nasconde il player audio e mostra quello video
                    $("#jquery_jplayer_2").hide();
                    $("#jp_container_2").hide();
                    $("#jp_container_1").show();
                    
                    $("#adminModalMultimediaViewLabel").html("Video felice ");
                    // carico il video
                    $("#jquery_jplayer_1").jPlayer("clearMedia");
                    $("#jquery_jplayer_1").jPlayer("setMedia", {
                        m4v: "/Universes/"+planetsObjs[position].happyVideo
                    });
                    $("#jp_container_1 div.jp-title h4").html(planetsObjs[position].happyVideoTitle);
                    $("#jp_container_1 div.jp-title li").html(planetsObjs[position].happyVideoDesc);
                    
                    $('#adminModalMultimediaView').modal('show');
                    break;
                case "audio":
                    // nella finestra modale nasconde il player video e mostra quello audio
                    $("#jquery_jplayer_2").show();
                    $("#jp_container_2").show();
                    $("#jp_container_1").hide();
                    
                    $("#adminModalMultimediaViewLabel").html("Audio felice ");
                    
                    $("#jquery_jplayer_2").jPlayer("clearMedia");
                    $("#jquery_jplayer_2").jPlayer("setMedia", {
                        mp3: "/Universes/"+planetsObjs[position].happyAudio
                    });
                    
                    $("#jp_container_2 div.jp-title h4").html(planetsObjs[position].happyAudioTitle);
                    $("#jp_container_2 div.jp-title li").html(planetsObjs[position].happyAudioDesc);
                    
                    $('#adminModalMultimediaView').modal('show');
                    break;
            }
        });
        $("#admin-planets table tbody").on("click",".set-sad",function(e) {
            e.preventDefault();
            var type = getRealIdFromFake($(this).parent().attr("class"));
            var idPlanet = getRealIdFromFake($(this).parent().parent().attr("id"));
            var position = findIdPlanetInPlanetObjs(idPlanet);
//            alert(position);
            var writeHtml = "";
            switch (type)
            {
                case "image":
                    var description = planetsObjs[position].sadImageSetDesc;
//                    alert("description: "+description);
//                      alert("description lunga: "+description.length);
                    if(description.length <= 1){
//                        alert("è vuota");
                        description = "- Nessuna descrizione fornita -";
                    }
                    
                    $("#adminModalImageViewLabel").html("Immagini non felici");
                    // carico lista immagini
                    
                    $.each(planetsObjs[position].sadImageSet, function(i){
                        if(i == 0)
                            writeHtml += "<div class=\"active item\"><img src=\"Universes/"+this+"\" /><div class=\"carousel-caption\"><h4>Descrizione</h4><p>"+description+"</p></div></div>";
                        else
                            writeHtml += "<div class=\"item\"><img src=\"Universes/"+this+"\" /><div class=\"carousel-caption\"><h4>Descrizione</h4><p>"+description+"</p></div></div>";
                        
                    });
                    $('#image-carousel .carousel-inner').html(writeHtml);
                    $('#adminModalImageView').modal('show');
                    break;
                case "video":
                    // nella finestra modale nasconde il player audio e mostra quello video
                    $("#jquery_jplayer_2").hide();
                    $("#jp_container_2").hide();
                    $("#jp_container_1").show();
                    
                    $("#adminModalMultimediaViewLabel").html("Video non felice ");
                    // carico il video
                    $("#jquery_jplayer_1").jPlayer("clearMedia");
                    $("#jquery_jplayer_1").jPlayer("setMedia", {
                        m4v: "/Universes/"+planetsObjs[position].sadVideo
                    });
                    $("#jp_container_1 div.jp-title h4").html(planetsObjs[position].sadVideoTitle);
                    $("#jp_container_1 div.jp-title li").html(planetsObjs[position].sadVideoDesc);
                    
                    $('#adminModalMultimediaView').modal('show');
                    break;
                case "audio":
                    // nella finestra modale nasconde il player video e mostra quello audio
                    $("#jquery_jplayer_2").show();
                    $("#jp_container_2").show();
                    $("#jp_container_1").hide();
                    
                    $("#adminModalMultimediaViewLabel").html("Audio non felice ");
                    
                    $("#jquery_jplayer_2").jPlayer("clearMedia");
                    $("#jquery_jplayer_2").jPlayer("setMedia", {
                        mp3: "/Universes/"+planetsObjs[position].sadAudio
                    });
                    
                    $("#jp_container_2 div.jp-title h4").html(planetsObjs[position].sadAudioTitle);
                    $("#jp_container_2 div.jp-title li").html(planetsObjs[position].sadAudioDesc);
                    
                    $('#adminModalMultimediaView').modal('show');
                    break;
            }
        });
        $("#admin-planets table tbody").on("click",".view-info",function(e) {
            var idPlanet = getRealIdFromFake($(this).parent().parent().attr("id"));
            var position = findIdPlanetInPlanetObjs(idPlanet);
//            alert("fratello "+$(this).next().length+", popover: "+$(this).next().hasClass("popover"));
            if($(this).next().length && $(this).next().hasClass("popover")){
                $(this).popover('destroy');
            } else {
                $(this).popover({
                    placement: "left",
                    title: "Descrizione",
                    content: planetsObjs[position].info
                });
                $(this).popover('show');
            }
        });
        
        /**
         * permette di stoppare il video se si clicca sul bottone close mentre è in esecuzione
         */
        $("#admin-close-video-button").on("click", function(e){
            e.preventDefault();
            $("#jquery_jplayer_1").jPlayer("stop");
            $("#jquery_jplayer_2").jPlayer("stop");
        });
        
    }
    
    
    
    function getAllUsers(firstTime) {
        $.get("/AdminUserServlet", {
        }).done(function(jsonUsers) {

            var obj = $.parseJSON(jsonUsers);
            var htmlUsers = "";

            $.each(obj, function(x) {
                var textualPrivilege = "";
                switch (this['privilege'])
                {
                    case 1:
                        textualPrivilege = "<span class=\"badge badge-success\">Creatore</span>";
                        break;
                    case 2:
                        textualPrivilege = "<span class=\"badge badge-info\">Amministratore</span>";
                        break;
                    default:
                        textualPrivilege = "<span class=\"badge badge-warning\">In Approvazione</span>";
                }

                htmlUsers += "<tr id=user-" + this['idUser'] + ">";
                htmlUsers += "<td>" + this['name'] + "</td>";
                htmlUsers += "<td><a href=\"mailto:" + this['email'] + "\">" + this['email'] + "</a></td>";
                htmlUsers += "<td>" + this['qualification'] + "</td>";
                htmlUsers += "<td class=\"privileges\" data-privileges=\"priv-" + this['privilege'] + "\">" + textualPrivilege + "</td>";
                htmlUsers += "<td>";
                htmlUsers += "<button class=\"btn btn-warning edit-user\"><i class=\"icon-pencil icon-white\"></i></button> ";
                htmlUsers += "<button class=\"btn btn-danger delete-user\"><i class=\"icon-remove icon-white\"></i></button>";
                htmlUsers += "</td>";
                htmlUsers += "</tr>";
            });

            $('#admin-users table tbody').html(htmlUsers);
            $("#tot-users strong").text(obj.length);
            
            if(firstTime)
                enableAdminController();
        });
    }
    function getAllUniverse() {
        $.get("/AdminUniverseServlet", {
        }).done(function(jsonUsers) {

            var obj = $.parseJSON(jsonUsers);
            var htmlUniverse = "";

            $.each(obj, function(x) {
                var textualValidation = "";
                
                if (this['isValidated'] === 1) {
                    textualValidation = "<span class=\"badge badge-success\">Validato e pubblicato</span>";
                } else
                if (this['isReady'] === 0) {
                    textualValidation = "<span class=\"badge\">In creazione</span>";
                } else 
                if (this['isReady'] === 1) {
                    textualValidation = "<span class=\"badge badge-warning\">In attesa di validazione</span>";
                }
                
                htmlUniverse += "<tr id=universe-" + this['idUniverse'] + ">";
                htmlUniverse += "<td>" + this['nameUniverse'] + "</td>";
                htmlUniverse += "<td class=\"universe-description\">"+this['descriptionUniverse']+"</td>";
                htmlUniverse += "<td class=\"number-planet\"><strong>"+this['numberPlanets']+"</strong> <button class=\"btn btn-info admin-planets\"><i class=\"icon-eye-open icon-white\"></i></button></td>"
                htmlUniverse += "<td id=\"creator-"+this['idCreator']+"\" class=\"creator-name\">"+this['creatorName']+"</td>";
                htmlUniverse += "<td class=\"validation\" data-validation=\"validation-" + this['isValidated'] + "\">" + textualValidation + "</td>";
                htmlUniverse += "<td>";
                if(this['isValidated'] === 0){
                htmlUniverse += "<button class=\"btn btn-success admin-planet-action-accept";
                    if(this['isReady'] === 0)
                        htmlUniverse += " disabled\" disabled=\"disabled\"><i class=\"icon-ok icon-white\"></i></button> ";
                    else
                        htmlUniverse += "\"><i class=\"icon-ok icon-white\"></i></button> ";
                }
                htmlUniverse += "<button class=\"btn btn-danger admin-planet-action-reject\"><i class=\"icon-remove icon-white\"></i></button>";
                htmlUniverse += "</td>";
                htmlUniverse += "</tr>";
            });

            $('#admin-universe table tbody').html(htmlUniverse);
            $("#tot-universes strong").text(obj.length);
//            enableAdminController(); // da chiamare una volta sola!
        });
    }
//    function getUniverseForUser(userId) {
//        // TODO
//    }
    var happyImageSet = [];
    var sadImageSet = [];
    var planetsObjs = [];
    function getPlanets(universe) {
        $.get("/AdminUniverseServlet", {
            selectedUniverse: universe
        }).done(function(jsonPlanets) {

            var obj = $.parseJSON(jsonPlanets);
            var htmlPlanets = "";
            planetsObjs.length = 0;
            happyImageSet.length = 0;
            sadImageSet.length = 0;
            $.each(obj, function(x) {
                var htmlCheck = "";
                switch (this['isControlled'])
                {
                    case "0":
                        htmlCheck = "<input type=\"checkbox\" />";
                        break;
                    case "1":
                        htmlCheck = "<input type=\"checkbox\" checked=\"checked\" />";
                        break;
                }
                
                
                var happyPhotos = [];
                var sadPhotos = [];
                
                $.each(this["pathPhotoHappy"], function(i) {
                    happyPhotos.push(this);
                });
                $.each(this["pathPhotoSad"], function(i) {
                    sadPhotos.push(this);
                });
                var imageColumnHtml = "";
                if(happyPhotos.length !== 0)
                    imageColumnHtml += "<button class=\"btn btn-mini btn-success set-happy\"><i></i></button> ";
                if(sadPhotos.length !== 0)
                    imageColumnHtml += "<button class=\"btn btn-mini btn-danger set-sad\"><i></i></button>";
                
                var audioColumnHtml = "";
                var videoColumnHtml = "";
                if(this['audioHappyPath'] !== ""){
                    audioColumnHtml += "<button class=\"btn btn-mini btn-success set-happy\"><i></i></button> ";
                }
                
                if (this['audioSadPath'] !== "") {
                    audioColumnHtml += "<button class=\"btn btn-mini btn-danger set-sad\"><i></i></button>";
                }

                if (this['videoHappyPath'] !== "") {
                    videoColumnHtml += "<button class=\"btn btn-mini btn-success set-happy\"><i></i></button> ";
                }

                if (this['videoSadPath'] !== "") {
                    videoColumnHtml += "<button class=\"btn btn-mini btn-danger set-sad\"><i></i></button>";
                }

                if (videoColumnHtml === "") {
                    videoColumnHtml = "<span class=\"badge badge-important\"><i class=\"icon-remove icon-white\"></i></span>";
                }
                if (audioColumnHtml === "") {
                    audioColumnHtml = "<span class=\"badge badge-important\"><i class=\"icon-remove icon-white\"></i></span>";
                }
                if (imageColumnHtml === "") {
                    imageColumnHtml = "<span class=\"badge badge-important\"><i class=\"icon-remove icon-white\"></i></span>";
                }
                
                var currentPlanetObj = {
                    idPlanet:this['idPlanet'],
                    happyImageSet:happyPhotos,
                    happyImageSetDesc: this['descriptionPhotoHappy'],
                    sadImageSet:sadPhotos,
                    sadImageSetDesc: this['descriptionPhotoSad'],
                    
                    happyAudio:this['audioHappyPath'],
                    happyAudioTitle: this["audioHappyTitle"],
                    happyAudioDesc: this["audioHappyDescription"],
                    
                    sadAudio:this['audioSadPath'],
                    sadAudioTitle: this["audioSadTitle"],
                    sadAudioDesc: this["audioSadDescription"],
                    
                    happyVideo:this['videoHappyPath'],
                    happyVideoTitle: this["videoHappyTitle"],
                    happyVideoDesc: this["videoHappyDescription"],
                    
                    sadVideo:this['videoSadPath'],
                    sadVideoTitle: this["videoSadTitle"],
                    sadVideoDesc: this["videoSadDescription"],
                    
                    info: this['infoPlanet']
                };
                planetsObjs.push(currentPlanetObj);
                
                htmlPlanets += "<tr id=planet-" + this['idPlanet'] + ">";
                htmlPlanets += "<td>" + htmlCheck + "</td>";
                htmlPlanets += "<td><p><strong>Titolo completo:</strong> "+this['shortLabel']+"</p><p><strong>Titolo prima riga: </strong>"+this['titolo1']+"<br /><strong>Titolo seconda riga: </strong>"+this['titolo2']+"<br /><strong>Titolo terza riga: </strong>"+this['titolo3']+"</p></td>";
                htmlPlanets += "<td class=\"column-image\">"+imageColumnHtml+"</td>";
                htmlPlanets += "<td class=\"column-audio\">"+audioColumnHtml+"</td>";
                htmlPlanets += "<td class=\"column-video\">" + videoColumnHtml + "</td>";
                htmlPlanets += "<td><button class=\"btn btn-info view-info\"><i class=\"icon-info-sign icon-white\"></i></button></td>";
                htmlPlanets += "</tr>";
            });
            if(htmlPlanets !== "")
                $('#admin-planets table tbody').html(htmlPlanets);
            $("#tot-planets strong").text(obj.length);
//            enableAdminController(); // da chiamare una volta sola!
        });
    }
    
    function findIdPlanetInPlanetObjs(planet){
        
        var found = -1;
        $.each(planetsObjs, function(i){
//            alert(planet + " e' uguale a "+ this.idPlanet + " ?");
            if(this.idPlanet == planet){
                found = i;
            }
        });
        return found;
    }
    
    getAllUniverse();
    getAllUsers(true);
    $('#tab-admin-users').tab('show');
    $("#tab-admin-users").on('shown', function(e) {
        getAllUsers(false);
    });
    $("#tab-admin-universe").on('shown', function(e) {
        getAllUniverse();
    });
    $("#myCarousel").carousel({
        interval: false
    });
    
    $(".back-to-universes").click(function(e){
        $("#myCarousel").carousel('prev');
    });
    

    // titolo dinamico
    $('.nav-tabs a').on('shown', function(e) {
        var currentId = $(this).attr('id');

        $(".admin-titles .active").removeClass("active");
        $("#title-" + currentId).addClass("active");
    });
    
    /**
     * Taglio il testo della descrizione troppo lungo
     */
    $("#admin-universe .universe-description").expander({
        expandText: ' Mostra tutto <i class="icon-chevron-down"></i>',
        userCollapseText: '<p>Nascondi il testo <i class="icon-chevron-up"></i></p>'
    });
    
    $("#jquery_jplayer_1").jPlayer({
//        ready: function() {
//            $(this).jPlayer("setMedia", {
//                m4v: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v"
//            });
//        },
        swfPath: "js",
        supplied: "m4v",
        size: {
            width: "640px",
            height: "360px",
            cssClass: "jp-video-360p"
        },
        cssSelectorAncestor: '#jp_container_1',
        smoothPlayBar: true,
        keyEnabled: true
    });
    
    $("#jquery_jplayer_2").jPlayer({
        swfPath: "js",
        supplied: "mp3",
        wmode: "window",
        cssSelectorAncestor: '#jp_container_2',
        smoothPlayBar: true,
        keyEnabled: true
    });
    


    /* Prende in input una stringa tipo #FFFFFF o FFFFFF e ritorna un oggetto cha ha proprietà rbg decimali
     * 
     * @param {String} hex
     * @returns Una struttura con proprietà r, g, b. Ognuna rappresentante la proprietà del colore.
     */
    function hexToRgb(hex) {
        // nel caso venga passato il cancelletto lo elimina dalla stringa
        hex.replace("#", "");
        // Espande la forma a triplete (tipo "03F") nella forma estesa (analogamente "0033FF")
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, function(m, r, g, b) {
            return r + r + g + g + b + b;
        });

        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }
    /* Traduce un componente decimale in HEX
     * 
     * @param {String} c
     * @returns {String}
     */
    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }

    /* Prende in input i valori RGB e ritorna una stringa in esadecimale tipo #FFFFFF
     * 
     * @param {String} r
     * @param {String} g
     * @param {String} b
     * @returns {String} tipo #FFFFFF
     */
    function rgbToHex(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }

    function getType(tabId) {
        if (tabId === "tab-step231-happy" ||
                tabId === "tab-step233-sad" ||
                tabId === "tab-step231") {
            // è immagine
            return "image";
        } else {
            // è multimedia
            return "multimedia";
        }
    }

    function getHappinessFromTabId(tabId) {
        if (tabId.indexOf("-sad") == -1) { // felice
            return 1;
        } else { // triste
            return 0;
        }
    }

    $("#planetTabLv2-emotional li a, #planetTabLv2 li a").click(function() {
//        alert(currentActiveTab);
        var that = this;
        currentContentId = $("#" + currentActiveTab).attr("href");
//        alert(currentContentId);
        descriptionText = $(currentContentId + " textarea").val();
        var savedType = getType(currentActiveTab);

        $.post("/manageDescriptionServlet", {
            happiness: getHappinessFromTabId(currentActiveTab),
            description: descriptionText,
            type: savedType
        }).done(function(data) {
//            alert("description salvata: " + descriptionText + "tipo collection: " + savedType);
        });
        var gettingType = getType($(this).attr('id'));
        $.get("/manageDescriptionServlet", {
            happiness: getHappinessFromTabId($(this).attr('id')),
            type: gettingType
        }).done(function(gettedDesc) {
            var gettedContentId = $("#" + $(that).attr('id')).attr("href");
//            alert("ID: " + gettedContentId);
            $(gettedContentId + " textarea").val(gettedDesc);
//            alert("description ottenuta: " + gettedDesc + "tipo collection: " + gettingType);
        });

        currentActiveTab = $(this).attr('id');
    });

    /** Nascondo le sottotab della gestione dei contenuti tristi **/


    /** Gestione dei form/hints **/

    // suggerimento per l'avatar autogenerato
    $("#universe-avatar-img").popover();

    

    function checkFirstStepFields() {
        var checked = true;
        var nameContainer = $("#nameUniverse-container");
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("input:text")))
            checked = false;
        /*if(nameContainer.find("input:text").val().length < 2){
         checked = false;
         showErrorToContainer(nameContainer);
         }*/
        nameContainer = $("#descUniverse-container");
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("textarea")))
            checked = false;
        /*if(nameContainer.find("textarea").val().length < 2){
         checked = false;
         showErrorToContainer(nameContainer);
         }*/
        return checked;
    }

    function checkSecondStepFields() {
        var checked = true;
        var nameContainer = $("#firstLine-container"); // primo titolo
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("input:text")))
            checked = false;
        var nameContainer = $("#secondLine-container"); // secondo titolo
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("input:text")))
            checked = false;
        var nameContainer = $("#thirdLine-container"); // terzo titolo
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("input:text")))
            checked = false;
        var nameContainer = $("#labelPlanet-container"); // titolo galassia
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("input:text")))
            checked = false;
        nameContainer = $("#descPlanet-container");
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("textarea")))
            checked = false;
        /*if(nameContainer.find("textarea").val().length < 2){
         checked = false;
         showErrorToContainer(nameContainer);
         }*/
        return checked;
    }

    function hideErrorToContainer(nameContainer) {
        $(nameContainer).removeClass("error");
        $('.help-inline', nameContainer).fadeOut("slow");
        $('.help-block', nameContainer).fadeOut("slow");
    }

    function showErrorToContainer(nameContainer) {
        $(nameContainer).addClass("error");
        $('.help-inline', nameContainer).fadeIn("slow");
        $('.help-block', nameContainer).fadeIn("slow");
    }


    $("#first-step-submit").submit(function(event) {
        event.preventDefault();
        $("#tab-step2").click();

    });


    /*$("#add-tag").click(function(e){
     e.preventDefault();
     
     $(this).popover({
     html : true,
     content: function() {
     return $('#popover_content_wrapper').html();
     }
     
     });
     });*/

    var $container;
    var $popover;
    function generatePopover() {

        $popover = $("#add-tag").popover({
            html: true,
            content: function() {
                return $('#popover_content_wrapper').html();
            },
            container: $container,
            trigger: 'manual'

        });

        $popover.on('shown', function() {


        });
    }

    $(this).on("click", ".popover-content a", function(e) {
        e.preventDefault();
        //alert("culo"); // TODO: GESTIONE TAG AGGIUNTA
        $popover.popover('toggle');
        $popover.popover('destroy');
        var newTag = $(this).parent().find("input:text").val();

        $.post("/insertTagServlet", {
            editingPlanetId: globalIdPlanet,
            tagName: newTag
        }).done(function(data) {
//            alert("Tutto Ok:" + data);

            $("#tags-container .controls #add-tag").before("<span id=\"" + data + "\" class=\"badge badge-info\">" + newTag + " <a href=\"#\" class=\"remove-tag\"><i class=\"icon-remove\"></i></a></span>&nbsp;");
            //$("#tags-container .controls #add-tag").before("<span id=\"" + 1 + "\" class=\"badge badge-info\">" + newTag + " <a href=\"#\" class=\"remove-tag\"><i class=\"icon-remove\"></i></a></span>&nbsp;");

        });

        // alert("aggiungi al db il tag: " + newTag);
        // $("#tags-container .controls #add-tag").before("<span class='badge badge-info'>" + newTag + "</span>\n");
    });


    $(this).on("click", "#add-tag", function(e) {
        e.preventDefault();
//        alert("click");
        generatePopover();
        $popover.popover('show');
    });

    $(this).on("click", "#add-tag-btn", function(event) {
        event.preventDefault();
//        alert("pre ajax");
        /*var newTag = $("input:text",this).val();
         alert("aggiungi al db il tag: "+newTag);
         $("#tags-container .controls").append("<span class='badge badge-info'>"+newTag+"</span>");*/
    });

    $(this).on("mouseleave", ".popover", function() {

        $popover.popover('toggle');
    });

    $(this).on("click", ".remove-tag", function(e) {
        e.preventDefault();

        var tag = $(this).parent().attr("id");
        var that = this;
//        alert("rimuovo tag: " + tag + " in " + globalIdPlanet);

        $.post("/deleteTagServlet", {// TODO: gestione tag cancellazione
            editingPlanetId: globalIdPlanet,
            tagId: tag
        }).done(function(data) {
//            alert("Tutto Ok rimozione:" + data + " - this:" + $(that).html());

            $(that).parent().remove();
        });
    });

    /** Gestione della griglia degli universi/pianeti **/

    // suggerimento per eliminare
    //$(".delete-drag-drop").popover();

    if ($("#universe-selection").length) {
        $("#universe-selection li").draggable({
            handle: ".universe-avatar",
            cursor: "move",
            opacity: 0.7,
            scroll: false,
            revert: "invalid",
            revertDuration: 500,
            appendTo: "body"
        });

        $("#universe-delete").droppable({
            activeClass: "droppable-hover",
            hoverClass: "ui-state-active",
            drop: function(event, ui) {
                var universeTitle = $("h4", ui.draggable).text();
                $("#myModalLabel").text("Conferma eliminazione");
                $("#myModal .modal-body p").html("Vuoi cancellare l'Universo <strong>" + universeTitle + "</strong> ?");
                $('#myModal').modal('show');

                $("#delete-confirm").click(function() {

                    var idUniverse = $("div", ui.draggable).attr("id");
                    $.post("/deleteUniverseServlet", {
                        u: idUniverse
                    }).done(function(data) {
                        setTimeout(function() {
                            $(ui.draggable).toggle("explode", {}, 1500);
                            $(ui.draggable).remove();
                        }, 500);
                    });

                });
                $("#delete-cancel").click(function() {
                    //alert(ui.draggable.toString());
                    $("#universe-selection li").animate({
                        left: 0,
                        top: 0
                    });
                    /*
                     $(ui.draggable).draggable("option", "revert", true);
                     setTimeout(function() {
                     $("ui.draggable").draggable("option", "revert", "invalid");
                     }, 1000);*/
                });

            },
            over: function(event, ui) {
                $("button", this).css('zIndex', 20).show();
                //$( ui.draggable ).effect( "size", { to: { width: 50, height: 50 } }, 0 );
            },
            tolerance: 'pointer'
        });

        $("#universe-selection li").disableSelection();

        /*
         $(".universe-avatar button").click(function(){
         alert("Creo un nuovo universo, redirect in corso...");
         window.location.replace("/firstStepServlet");
         });
         
         $(".edit-universe").click(function(){
         alert($(this).parent().parent().find("div").attr("id"));
         });
         */

    }

    // $("#connectionModal").text("Conferma eliminazione");
    // $("#connectionModal .modal-body p").html("Vuoi cancellare l'Universo <strong>" + universeTitle + "</strong> ?");
    // $('#connectionModal').modal('show');

    /*$("#delete-confirm").click(function() {
     
     var idUniverse = $("div", ui.draggable).attr("id");
     
     $.post("/deleteUniverseServlet", {
     u : idUniverse
     }).done(function(data) {
     alert("Tutto Ok:" + data);
     setTimeout(function() {
     $(ui.draggable).toggle("explode", {}, 1500);
     $(ui.draggable).remove();
     }, 500);
     });
     
     
     
     });*/


    function enableDraggablePlanets() {

        if ($("#planet-selection").length) {
            $("#planet-selection li").draggable({
                handle: ".planet-avatar",
                cursor: "move",
                opacity: 0.7,
                scroll: false,
                revert: "invalid",
                revertDuration: 500,
                appendTo: "body",
                cancel: false
            });

            $("#planet-delete").droppable({
                activeClass: "droppable-hover",
                hoverClass: "ui-state-active",
                drop: function(event, ui) {
                    var universeTitle = $("h4", ui.draggable).text();
                    $("#myModalLabel").text("Conferma eliminazione");
                    $("#myModal .modal-body p").html("Vuoi cancellare il Pianeta <strong>" + universeTitle + "</strong> ?");
                    $('#myModal').modal('show');

                    deletingPlanet = ui.draggable;

                    $("#delete-confirm").click(function() {

                        var idPlanet = $(deletingPlanet).attr("id");

//                        alert("Pianeta da cancellare:" + idPlanet);
                        $.post("/deletePlanetServlet", {
                            p: idPlanet
                        }).done(function(data) {
//                            alert("Pianeta cancellato:" + data);
                            setTimeout(function() {
                                $(deletingPlanet).toggle("explode", {}, 1500);
                                $(deletingPlanet).remove();
                            }, 500);
                        });

                    });
                    $("#delete-cancel").click(function() {
                        //alert(ui.draggable.toString());
                        $("#planet-selection li").animate({
                            left: 0,
                            top: 0
                        });
                        /*
                         $(ui.draggable).draggable("option", "revert", true);
                         setTimeout(function() {
                         $("ui.draggable").draggable("option", "revert", "invalid");
                         }, 1000);*/
                    });

                },
                over: function(event, ui) {
                    $("button", this).css('zIndex', 20).show();
                    //$( ui.draggable ).effect( "size", { to: { width: 50, height: 50 } }, 0 );
                },
                tolerance: 'pointer'
            });

            $("#planet-selection li").disableSelection();

            $(".planet-avatar button.edit-planet").click(function() {
                if (!$("#planet-selection li").is('.ui-draggable-dragging')) {
//                    alert("Sto modificando il pianeta " + $(this).parent().parent().attr("id"));
                    globalIdPlanet = $(this).parent().parent().attr("id");

                    $.get("/secondStepServlet", {
                        editingPlanetId: globalIdPlanet,
                        editingUniverseId: globalIdUniverse
                    }).done(function(data) {
                        //alert("Tutto Ok:" + data);

                        var obj = $.parseJSON(data);
                        var firstRow = obj.firstRow;
                        var secondRow = obj.secondRow;
                        var thirdRow = obj.thirdRow;
                        var shortLabel = obj.shortLabel;
                        var descriptionPlanet = obj.descriptionPlanet;

                        var tags = "";

//                        alert(data);
                        $('#firstLine').val(firstRow);
                        $('#firstLine').keyup();
                        $('#secondLine').val(secondRow);
                        $('#secondLine').keyup();
                        $('#thirdLine').val(thirdRow);
                        $('#thirdLine').keyup();
                        $('#labelPlanet').val(shortLabel);
                        $('#labelPlanet').keyup();
                        $('#descPlanet').val(descriptionPlanet);




                        $.each(obj.arrayTag, function(x, tag) {
                            tags += "<span id=\"" + tag.idTag + "\" class=\"badge badge-info\">" + tag.tagValue + " <a href=\"#\" class=\"remove-tag\"><i class=\"icon-remove\"></i></a></span>";
                        });

                        $("#tags-container").find("div").html(tags);
                        $("#tags-container").find("div").append("<a href=\"#\" id=\"add-tag\"><span class=\"badge badge-success\"><i class=\"icon-plus icon-white\"></i></span></a>");
                        planetSelected = true;

                        $("#tab-step22").click();
                    });

                }

            });
            $(".planet-avatar button.new-planet").click(function(e) {
                e.preventDefault();
//                alert("Sto creando un nuovo pianeta");
                if (!$("#planet-selection li").is('.ui-draggable-dragging')) {
                    globalIdPlanet = $(this).parent().parent().attr("id");

                    $.get("/secondStepServlet", {
                        editingPlanetId: globalIdPlanet,
                        editingUniverseId: globalIdUniverse
                    }).done(function(data) {

                        var obj = $.parseJSON(data);
                        var firstRow = obj.firstRow;
                        var secondRow = obj.secondRow;
                        var thirdRow = obj.thirdRow;
                        var shortLabel = obj.shortLabel;
                        var descriptionPlanet = obj.descriptionPlanet;

                        var tags = "";

                        globalIdPlanet = obj.idPlanet;
//                        alert("modificato " + globalIdPlanet);
                        $('#firstLine').val(firstRow);
                        $('#firstLine').keyup();
                        $('#secondLine').val(secondRow);
                        $('#secondLine').keyup();
                        $('#thirdLine').val(thirdRow);
                        $('#thirdLine').keyup();
                        $('#labelPlanet').val(shortLabel);
                        $('#labelPlanet').keyup();
                        $('#descPlanet').val(descriptionPlanet);

                        $("#tags-container").find("div").html(tags);
                        $("#tags-container").find("div").append("<a href=\"#\" id=\"add-tag\"><span class=\"badge badge-success\"><i class=\"icon-plus icon-white\"></i></span></a>");

                        planetSelected = true;

                        $("#tab-step22").click();
                    });

                }

            });

        }

        $(".ui-state-disabled").draggable("option", "disabled", true);

    }


    /*$("#delete-confirm").click(function() {
     
     var idUniverse = $("div", ui.draggable).attr("id");
     
     $.post("/deleteUniverseServlet", {
     u : idUniverse
     }).done(function(data) {
     alert("Tutto Ok:" + data);
     setTimeout(function() {
     $(ui.draggable).toggle("explode", {}, 1500);
     $(ui.draggable).remove();
     }, 500);
     });
     
     });*/

    $("#to-content-button").click(function() { // TODO: mettere metodo .on!!!
        $("#tab-step23").click();

//        if (checkSecondStepFields()) {
//            // globalIdPlanet = $(this).parent().parent().attr("id");
//
//            $.post("/secondStepServlet", {
//                editingPlanetId: globalIdPlanet,
//                editingUniverseId: globalIdUniverse,
//                title1: $('#firstLine').val(),
//                title2: $('#secondLine').val(),
//                title3: $('#thirdLine').val(),
//                shortLabel: $('#labelPlanet').val(),
//                description: $('#descPlanet').val()
//            }).done(function(data) {
//                //alert("Tutto Ok:" + data);
//
//                alert(data);
//
//                $("#accordion-step3").click();
//            });
//        }
    });

    /** Ricerca universo**/
    $('#universe-search').keyup(function(event) {
        var search_text = $(this).val();
        var rg = new RegExp(search_text, 'i');
        $('#universe-selection li h4').each(function() {
            if ($.trim($(this).html()).search(rg) == -1) {
                $(this).parent().parent().hide("slow");
            } else {
                $(this).parent().parent().show("slow");
            }
        });
    });
    /** Ricerca pianeta **/
    $('#planet-search').keyup(function(event) {
        var search_text = $(this).val();
        var rg = new RegExp(search_text, 'i');
        $('#planet-selection li h4').each(function() {
            if ($.trim($(this).html()).search(rg) == -1) {
                $(this).parent().fadeOut("slow");
            } else {
                $(this).parent().fadeIn("slow");
            }
        });
    });
    // tasto clear
    $('#planet-clear').click(function() {
        $('#planet-search').val('');
        $('#planet-selection li').each(function() {
            $(this).fadeIn("slow");
        });
    });

    var charFirstLine = 0;
    var charSecondLine = 0;
    var charThirdLine = 0;
    var charPreview = 0;
    var lastValFirstLine;
    var lastValSecondLine;
    var lastValThirdLine;
    var lastValPreview;

    // per l'anteprima può essere utile un listener del genere
    $('#firstLine').keyup(function() {
        //console.log("dimensione: ", $(this).width());
        charFirstLine = $(this).val().length;
        if (charFirstLine < 12) {
            lastValFirstLine = $(this).val();
            $('.planetBig-preview .line1').text(lastValFirstLine);
            $(this).tooltip('destroy');
        } else {
            $(this).val(lastValFirstLine);
            $(this).tooltip({
                placement: 'bottom',
                trigger: 'manual'
            });
            var that = this;
            $(this).tooltip("show");
            setTimeout(function() {
                $(that).tooltip("destroy");
            }, 4000);
        }
    });
    $('#secondLine').keyup(function() {
        charSecondLine = $(this).val().length;
        if (charSecondLine < 12) {
            lastValSecondLine = $(this).val();
            $('.planetBig-preview .line2').text(lastValSecondLine);
            $(this).tooltip('destroy');
        } else {
            $(this).val(lastValSecondLine);
            $(this).tooltip({
                placement: 'bottom',
                trigger: 'manual'
            });
            var that = this;
            $(this).tooltip("show");
            setTimeout(function() {
                $(that).tooltip("destroy");
            }, 4000);
        }
    });
    $('#thirdLine').keyup(function() {
        charThirdLine = $(this).val().length;
        if (charThirdLine < 11) {
            lastValThirdLine = $(this).val();
            $('.planetBig-preview .line3').text(lastValThirdLine);
            $(this).tooltip('destroy');
        } else {
            $(this).val(lastValThirdLine);
            $(this).tooltip({
                placement: 'bottom',
                trigger: 'manual'
            });
            var that = this;
            $(this).tooltip("show");
            setTimeout(function() {
                $(that).tooltip("destroy");
            }, 4000);
        }
    });

    $('#labelPlanet').keyup(function() {
        charPreview = $(this).val().length;
        if (charPreview < 30) {
            lastValPreview = $(this).val();
            $('.planetSmall-preview p').text(lastValPreview);
        } else {
            $(this).val(lastValPreview);
        }
    });

    // hack agli input type=file
    /*
     $('input[id=file]').change(function() {
     $('#pretty-input').val($(this).val().replace("C:\\fakepath\\", ""));
     });
     /*
     
     // per disabilitare gli accordion usa un controllo qui, per fare l'overriding usa:
     /*$('#myLink').click(function(e) {
     e.preventDefault();
     //do other stuff when a click happens
     });*/

    // Initialize the jQuery File Upload widget:
    //$('#fileupload').fileupload();

    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: '/UploadServlet',
        formData: {happiness: '1'}
    });

    $('#fileupload2').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: '/UploadAudioVideoServlet',
        formData: {happiness: '1'}
    });
    $('#fileupload3').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: '/UploadServlet',
        formData: {happiness: '0'}
    });
    $('#fileupload4').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: '/UploadAudioVideoServlet',
        formData: {happiness: '0'}
    });


// Load existing files:
//    $('#fileupload2').each(function() {
//        var that = this;
//        $.getJSON(this.action, function(result) {
//            if (result && result.length) {
//                $(that).fileupload('option', 'done')
//                        .call(that, null, {result: result});
//            }
//        });
//    });
    // Load existing files:
//    $('#fileupload').each(function () {
//        var that = this;
//        $.getJSON(this.action, function (result) {
//            alert();
//            if (result && result.length) {
//                $(that).fileupload('option', 'done')
//                    .call(that, null, {result: result});
//            }
//        });
//    });





    /*
     *  This file contains the JS that handles the first init of each jQuery demonstration, and also switching
     *  between render modes.
     */
    jsPlumb.bind("ready", function() {

        //jsPlumb.DemoList.init();

        // chrome fix.
        document.onselectstart = function() {
            return false;
        };

        // render mode
        var resetRenderMode = function(desiredMode) {
            var newMode = jsPlumb.setRenderMode(desiredMode);
//            $(".rmode").removeClass("selected");
//            $(".rmode[mode='" + newMode + "']").addClass("selected");
//
//            $(".rmode[mode='canvas']").attr("disabled", !jsPlumb.isCanvasAvailable());
//            $(".rmode[mode='svg']").attr("disabled", !jsPlumb.isSVGAvailable());
//            $(".rmode[mode='vml']").attr("disabled", !jsPlumb.isVMLAvailable());

            jsPlumbDemo.init();
        };
        resetRenderMode(jsPlumb.SVG);

    });

    // aggiungere endpoint programmatically


    $("#tab-step3").on('shown', function(e) {
        jsPlumbDemo.init();
        jsPlumb.repaintEverything();
        connections.length = 0;
        $.get("/connectionsServlet", {
        }).done(function(data) {

            var obj = $.parseJSON(data);
            var connections = "";
            var planetsEndPoint = "";
//                planetsArray.length = 0;
            automaticAdd = true;
            $.each(obj, function(x) {

                connectPlanet(this['startPlanet'], this['destinationPlanet'], this['r'], this['g'], this['b']);

            });
            automaticAdd = false;

        });


    });



//    Metodo richiamato PRIMA di lanciare il .show() sulla tab appropriata
    $("#tab-step23").click(function() {

        if (planetSelected && checkSecondStepFields()) {
            // globalIdPlanet = $(this).parent().parent().attr("id");

            $.post("/secondStepServlet", {
                editingPlanetId: globalIdPlanet,
                editingUniverseId: globalIdUniverse,
                title1: $('#firstLine').val(),
                title2: $('#secondLine').val(),
                title3: $('#thirdLine').val(),
                shortLabel: $('#labelPlanet').val(),
                description: $('#descPlanet').val()
            }).done(function(data) {
                //alert("Tutto Ok:" + data);

                $("#contentModalLabel").text("Utilizzare il filtro emozionale?");
//       $("#contentModal .modal-body p").html("Vuoi cancellare l'Universo <strong>" + universeTitle + "</strong> ?");
                $('#contentModal').modal('show');

                return true;

            });
        } else {
            return false;
        }
    });

    $("#emotionalContentChoose").click(function() {
        $("#loading-img").fadeOut("fast");
        $("#planetTabLv2").parent().fadeOut("fast");
        $("#planetTabLv2-emotional").parent().fadeIn("slow");

        $("#step231-happy").prepend($("#fileupload-container"));
        $("#fileupload-container").show();

        $("#step232-happy").prepend($("#fileupload-multimedia-container"));
        $("#fileupload-multimedia-container").show();

        $('.files tr.template-download').remove();


        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            data: {happiness: '1'},
            url: $('#fileupload').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload')[0]
        }).always(function(result) {
//                alert(result);
            $(this).removeClass('fileupload-processing');

        }).done(function(result) {
//                alert(result);
            $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
        });
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            data: {happiness: '1'},
            url: $('#fileupload2').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload2')[0]
        }).always(function(result) {
//                alert(result);
            $(this).removeClass('fileupload-processing');

        }).done(function(result) {
//                alert(result);
            $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
        });
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            data: {happiness: '0'},
            url: $('#fileupload3').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload3')[0]
        }).always(function(result) {
//                alert(result);
            $(this).removeClass('fileupload-processing');

        }).done(function(result) {
//                alert(result);
            $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
        });
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            data: {happiness: '0'},
            url: $('#fileupload4').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload4')[0]
        }).always(function(result) {
//                alert(result);
            $(this).removeClass('fileupload-processing');

        }).done(function(result) {
//                alert(result);
            $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
        });

        currentActiveTab = "tab-step231-happy";
        $("#" + currentActiveTab).click();

    });

    $("#nonEmotionalContentChoose").click(function() {
        $("#loading-img").fadeOut("fast");
        $("#planetTabLv2-emotional").parent().fadeOut("fast");
        $("#planetTabLv2").parent().fadeIn("slow");

        $("#step231").prepend($("#fileupload-container"));
        $("#fileupload-container").show();

        $("#step232").prepend($("#fileupload-multimedia-container"));
        $("#fileupload-multimedia-container").show();

        $('.files tr.template-download').remove();

        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            data: {happiness: '1'},
            url: $('#fileupload').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload')[0]
        }).always(function(result) {
//                alert(result);
            $(this).removeClass('fileupload-processing');

        }).done(function(result) {
//                alert(result);
            $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
        });
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            data: {happiness: '1'},
            url: $('#fileupload2').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload2')[0]
        }).always(function(result) {
//                alert(result);
            $(this).removeClass('fileupload-processing');

        }).done(function(result) {
//                alert(result);
            $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
        });
        currentActiveTab = "tab-step231";
        $("#" + currentActiveTab).click();
    });

    function connectPlanet(startPlanet, endPlanet, r, g, b) {
        alert(startPlanet + " ," + endPlanet);
        var conn = jsPlumb.connect({uuids: ["endpoint-" + startPlanet, "endpoint-" + endPlanet], editable: true});

        conn.setPaintStyle({
            lineWidth: 3,
            strokeStyle: "rgba(" + r + "," + g + "," + b + ",0.5)",
            joinstyle: "round"
                    //outlineColor:transparent,
                    //outlineWidth:7
        });
//        jsPlumb.connect({ source:"endpoint-"+startPlanet, target:"endpoint-"+endPlanet });
    }


    function addEndPointPlanet(compositeIdPlanet) {
        jsPlumb.addEndpoint(compositeIdPlanet,
                {
                    endpoint: "Dot",
                    paintStyle: {fillStyle: "rgba(255,255,255,0.5)", radius: 15},
                    isSource: true,
                    isTarget: true,
                    connector: ["Straight", /*{ stub:[40, 60], gap:10 }*/],
                    connectorStyle: {
                        lineWidth: 3,
                        strokeStyle: "rgba(255,255,255,0.5)",
                        joinstyle: "round",
                    },
                    connectorHoverStyle: {
                        lineWidth: 3,
                        strokeStyle: "rgba(255, 165, 0,0.5)"
                    },
                    dragOptions: {},
                    beforeDrop: function(params) {
                        return updateConnections(params.connection);
                    },
                    maxConnections: -1
                }
        , {anchor: "TopCenter", uuid: compositeIdPlanet});
    }


    $("#tab-step21").click(function() {
        if (planetSelected && checkSecondStepFields()) {

            $.post("/secondStepServlet", {
                editingPlanetId: globalIdPlanet,
                editingUniverseId: globalIdUniverse,
                title1: $('#firstLine').val(),
                title2: $('#secondLine').val(),
                title3: $('#thirdLine').val(),
                shortLabel: $('#labelPlanet').val(),
                description: $('#descPlanet').val()
            }).done(function(data) {
                //alert("Tutto Ok:" + data);
                planetSelected = false;
                getPlanets();
                return true;
            });


        } else {
            return false;
        }
    });

    $("#tab-step21").on('shown', function(e) {
        planetSelected = false;
    });

    $("#tab-step2").click(function(event) {
        event.preventDefault();
        return getPlanets();
    });

    $("#tab-step22").click(function() {
        hideErrorToContainer($("#firstLine-container"));
        hideErrorToContainer($("#secondLine-container"));
        hideErrorToContainer($("#thirdLine-container"));
        hideErrorToContainer($("#labelPlanet-container"));
        hideErrorToContainer($("#descPlanet-container"));
        if (planetSelected) {
            return true;
        } else {
            return false;
        }
    });

    if ($('#colorpicker1').length) {
        $('#colorpicker1').farbtastic(function(color) {
            $('#colorp1').css({'background-color': color});
            $("#currentColor").val(color);
        });
    }





});

